package com.example.springboot.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.HoneyLogs;
import com.example.springboot.common.LogType;
import com.example.springboot.common.Result;
import com.example.springboot.entity.Faculty;
import com.example.springboot.entity.User;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.service.FacultyService;
import com.example.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 学部类型相关接口
 */
@RestController
@RequestMapping("/faculty")
public class FacultyController {

    @Autowired
    FacultyService facultyService;

    @Autowired
    UserService userService;

    /**
     * 新增信息 post
     */
    @HoneyLogs(operation = "学部类型", type = LogType.ADD)
    @PostMapping("/add")
    public Result add(@RequestBody Faculty faculty) {
        try {
            if (faculty.getType().length() > 10 ) {//要求名字长度小于等于10
                return Result.error("学部名称过长");
            }
            faculty.setAddtime(DateUtil.now()); //获取当前的时间(格式: yyyy-mm-dd HH:MM:SS) 如果是today则是yyyy-mm-dd
            facultyService.save(faculty);//service中的函数
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {//数据库插入重复错误时报错
                return Result.error("学部重复");
            } else {
                return Result.error("系统错误");//其他报错
            }
        }
        return Result.success();
    }

    /**
     * 修改信息 put
     */
    @HoneyLogs(operation = "学部类型", type = LogType.UPDATE)
    @PutMapping("/update")
    public Result update(@RequestBody Faculty faculty) {
        try {
            if (faculty.getType().length() > 10 ) {//要求名字长度小于等于10
                return Result.error("学部名称过长");
            }
            facultyService.updateById(faculty);//service中的函数
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {//数据库插入重复错误时报错
                return Result.error("学部重复");
            } else {
                return Result.error("系统错误");//其他报错
            }
        }
        return Result.success();
    }

    /**
     * 删除信息
     */
    @HoneyLogs(operation = "学部类型", type = LogType.DELETE)
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        //如果该标签被使用则不能删除
        //user中被使用的标签转化为数组
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        List<User> userList = userService.list(queryWrapper);
        List<String> majorList = userList.stream().map(User::getMajor).distinct().collect(Collectors.toList());
        //如果标签中存在user表中则不能删除
        String id1 = facultyService.getById(id).getType();
        for (String s : majorList) {
            if (id1.equals(s)) {
                throw new ServiceException("该标签已被使用");
            }
        }
        facultyService.removeById(id);
        return Result.success();
    }


    /**
     * 批量删除信息
     */
    @HoneyLogs(operation = "学部类型", type = LogType.BATCH_DELETE)
    @DeleteMapping("/delete/batch")
    public Result batchDelete(@RequestBody List<Integer> ids) {
        //如果该标签被使用则不能删除
        //user中被使用的标签转化为数组
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        List<User> userList = userService.list(queryWrapper);
        List<String> majorList = userList.stream().map(User::getMajor).distinct().collect(Collectors.toList());
        List<Faculty> facultyList = facultyService.listByIds(ids);
        List<String> type = facultyList.stream().map(Faculty::getType).collect(Collectors.toList());
        //如果标签中存在user表中则不能删除
        for (String s : majorList) {
                if ( type.contains(s)) {
                    throw new ServiceException("有标签已被使用");
                }
        }
        facultyService.removeBatchByIds(ids);
        return Result.success();
    }

    /**
     * 多条件模糊查询信息
     * pageNum 当前的页码
     * pageSize 每页查询的个数
     */
    @GetMapping("/selectByPage")
    public Result selectByPage(@RequestParam Integer pageNum,
                               @RequestParam Integer pageSize,
                               @RequestParam String type
                               ) {
        QueryWrapper<Faculty> queryWrapper = new QueryWrapper<Faculty>().orderByDesc("id");  // 默认倒序，让最新的数据在最上面
        queryWrapper.like(StrUtil.isNotBlank(type), "type", type);
        Page<Faculty> page = facultyService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return Result.success(page);
    }

    /**
     * 查询所有，返回单个元素列（type）
     */
    @GetMapping("/selectAll")
    public Result selectAll() {
        QueryWrapper<Faculty> queryWrapper = new QueryWrapper<Faculty>().orderByDesc("id");  // 默认倒序，让最新的数据在最上面
        List<Faculty> facultyList = facultyService.list(queryWrapper);
        //select * from user order by id desc
        List<String> typeList = facultyList.stream().map(Faculty::getType).collect(Collectors.toList());
        return Result.success(typeList);
    }

}
